<template>
  <div class="amap">
    <div id="containerMap" :style="{ height: `calc(100vh - ${navHeight}px)` }"></div>
  </div>
</template>

<script setup>
import AMapLoader from '@amap/amap-jsapi-loader'
import { onMounted, ref } from 'vue'

const navHeight = ref(0)
onMounted(() => {
  const nav = document.getElementsByClassName('van-nav-bar')[0]
  navHeight.value = nav.clientHeight
})

const amap = ref(null) // 地图容器
const AMap = ref(null) // 地图实例
const coordinate = ref([]) // 当前中心点坐标
AMapLoader.load({
  key: window.AmapAK, // 申请好的Web端开发者Key，首次调用 load 时必填
  version: '2.0' // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
})
.then(AM => {
  AMap.value = AM
  amap.value = new AMap.value.Map('containerMap')

  positioning()
})
.catch(e => {
  console.error(e) //加载错误提示
})

const positioning = () => {
  AMap.value.plugin('AMap.Geolocation', function () {
    var geolocation = new AMap.value.Geolocation({
      enableHighAccuracy: true, //是否使用高精度定位，默认:true
      timeout: 10000, //超过10秒后停止定位，默认：5s
      position: 'RB', //定位按钮的停靠位置
      offset: [10, 20], //定位按钮与设置的停靠位置的偏移量，默认：[10, 20]
      zoomToAccuracy: true //定位成功后是否自动调整地图视野到定位点
    })
    geolocation.getCurrentPosition(function (status, result) {
      if (status == 'complete') {
        onComplete(result)
      } else {
        onError(result)
      }
    })
  })
}
//解析定位结果
function onComplete(data) {
  var str = []
  str.push('定位结果：' + data.position)
  str.push('定位类别：' + data.location_type)
  if (data.accuracy) {
    str.push('精度：' + data.accuracy + ' 米')
  } //如为IP精确定位结果则没有精度信息
  str.push('是否经过偏移：' + (data.isConverted ? '是' : '否'))
  const {lng, lat} = data.position
  coordinate.value = [lng, lat]
  amap.value.setZoomAndCenter(18, coordinate.value) // zoom 取值 3-18

  setMarker()
}
//解析定位错误信息
function onError(data) {
  console.log('失败原因排查信息:' + data.message + '</br>浏览器返回信息：' + data.originMessage);
}
const setMarker = function(){
  var marker = new AMap.value.Marker({
    position: coordinate.value,
    icon: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
    anchor:'bottom-center',
    offset: new AMap.value.Pixel(0, 0)
  });

  marker.setMap(amap.value);

  marker.setLabel({
    direction:'right',
    offset: new AMap.value.Pixel(10, 0),  //设置文本标注偏移量
    content: "<div class='info'>我是 marker 的 label 标签</div>", //设置文本标注内容
  });
}
</script>

<style lang="scss" scoped>
.amap {
  #containerMap {
    position: relative;
  }
}
</style>
